﻿using System.Collections.Generic;
using System.ComponentModel;

namespace CommonUtils.Models
{
    /// <summary>
    /// Provides common functionality for ModelBase classes
    /// </summary>
    public abstract class ModelBase : INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(params string[] properties)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                foreach (var property in properties)
                {
                    handler(this, new PropertyChangedEventArgs(property));
                }
            }
        }

        protected void RaisePropertyChanged(params string[] properties)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                foreach (var property in properties)
                {
                    handler(this, new PropertyChangedEventArgs(property));
                }
            }
        }

        //
        // 摘要:
        //     Assigns a new value to the property. Then, raises the PropertyChanged event if
        //     needed.
        //
        // 参数:
        //   propertyName:
        //     The name of the property that changed.
        //
        //   field:
        //     The field storing the property's value.
        //
        //   newValue:
        //     The property's value after the change occurred.
        //
        // 类型参数:
        //   T:
        //     The type of the property that changed.
        //
        // 返回结果:
        //     True if the PropertyChanged event has been raised, false otherwise. The event
        //     is not raised if the old value is equal to the new value.
        protected virtual bool Set<T>(string propertyName, ref T field, T newValue)
        {
            if (EqualityComparer<T>.Default.Equals(field, newValue))
            {
                return false;
            }

            field = newValue;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}

